package com.example.utils.common;

import org.apache.shiro.authz.AuthorizationException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 全局捕获异常和自定义全局捕获异常
 */
@ControllerAdvice  //不指定包默认加了@Controller和@RestController都能控制
//@ControllerAdvice(basePackages ="com.example.demo.controller")
public class MyControllerAdvice {
    @Value("${shiro.config.globalPrintEnable}")
    boolean globalPrintEnable;

    /**
     * 全局异常处理，反正异常返回统一格式的map
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result exceptionHandler(Exception ex) {
        if(globalPrintEnable){
            ex.printStackTrace();
        }
        Throwable cause = ex.getCause();
        if (cause instanceof AuthorizationException) {
            return Result.error("没有权限操作");
        } else {
            return Result.error("error");
        }
    }
}